package org.example.appstart;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;
import org.example.App;
import org.example.exception.ExceptionReporter;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.example.utlis.CmdUtils;
import org.example.utlis.FXUtils;
import org.example.utlis.JsonUtils;

public class StartAppManagerController {
    @FXML
    private TableView<StartAppInfo> tableView;
    private CmdUtils cmd;
    private Stage mStage;
    private String mDevice;
    private List<StartAppInfo> appInfoList = new ArrayList<>();
    private final String path = "../../config/start-app-info.json";
//    private final String path = "F:/start-app-info.json";
    private JsonUtils<StartAppInfo> mJsonUtils;
    private ChooseOverListener chooseOverListener;
    public interface ChooseOverListener {
        void onOver(ObservableList<StartAppInfo> selectedItems);
    }

    public void setChooseOverListener(ChooseOverListener chooseOverListener) {
        this.chooseOverListener = chooseOverListener;
    }

    public void initialize() {
        cmd = CmdUtils.getInstance();
        mJsonUtils = new JsonUtils<>(path, StartAppInfo.class);

        tableView.setPlaceholder(new Label("空白"));
        tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        ObservableList<? extends TableColumn<?, ?>> columns = tableView.getColumns();
        columns.get(0).setCellValueFactory(new PropertyValueFactory<>("alias"));
        columns.get(1).setCellValueFactory(new PropertyValueFactory<>("pkgName"));
        columns.get(2).setCellValueFactory(new PropertyValueFactory<>("mainActivity"));

        appInfoList = mJsonUtils.readFile();
        ObservableList<StartAppInfo> list = FXCollections.observableArrayList(appInfoList);
        tableView.setItems(list);
    }

    @FXML
    void onInsert() {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setTitle("录入当前应用");
        dialog.setHeaderText("请输入该应用别名");
        dialog.setContentText("别名:");
        App.useJMetro(dialog.getDialogPane().getScene());

        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()){
            String[] appinfo = cmd.getPkgNameCurrentFocusAndLauncherActivity(mDevice);

            for (StartAppInfo startAppInfo : appInfoList) {
                if (startAppInfo.getPkgName().equals(appinfo[0])) {
                    update(startAppInfo, new StartAppInfo(result.get(), appinfo[0], appinfo[1]));
                    return;
                }
            }
            appInfoList.add(new StartAppInfo(result.get(), appinfo[0], appinfo[1]));
            tableView.setItems(FXCollections.observableArrayList(appInfoList));
        }
    }

    private void update(StartAppInfo fromStartAppInfo, StartAppInfo toStartAppInfo) {
        appInfoList.remove(fromStartAppInfo);
        appInfoList.add(toStartAppInfo);
        tableView.setItems(FXCollections.observableArrayList(appInfoList));
    }

    @FXML
    void onChooseOver() {
        ObservableList<StartAppInfo> selectedItems = tableView.getSelectionModel().getSelectedItems();
        if (selectedItems.size() == 0) {
            FXUtils.initSimpleDialog("提示", "当前未选中应用！");
            return;
        }
        chooseOverListener.onOver(selectedItems);
        close();
    }

    @FXML
    void onDelete() {
        FXUtils.initSimpleDialog("删除选中", "确认要删除吗？", () -> {
            ObservableList<StartAppInfo> selectedItems = tableView.getSelectionModel().getSelectedItems();
            appInfoList.removeAll(selectedItems);
            tableView.setItems(FXCollections.observableArrayList(appInfoList));
        }, null);
    }

    @FXML
    void onCancel() {
        FXUtils.initSimpleDialog("退出", "是否保存修改？", () -> {
            onSave();
            close();
        }, () -> close());
    }
    @FXML
    void onSave() {
        mJsonUtils.writeFile(appInfoList);
    }
    @FXML
    void onSaveAndQuit() {
        onSave();
        close();
    }

    private void close() {
        Platform.runLater(() -> mStage.close());
    }
    public void setStage(Stage stage) {
        mStage = stage;
    }
    public void setDevice(String device) {
        mDevice = device;
    }

}
